package com.yao.yaooj.judge.codesandbox.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yao.yaooj.common.ErrorCode;
import com.yao.yaooj.exception.BusinessException;
import com.yao.yaooj.judge.codesandbox.CodeSandbox;
import com.yao.yaooj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yao.yaooj.judge.codesandbox.model.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 远程代码沙箱
 * 实际调用接口的沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {

    private static final String AUTH_REQUEST_HEADER = "auth"; //在请求头之间，传递字符串的方式，来鉴别这个字符串是否是服务器预先设定好的

    private static final String AUTH_REQUEST_SECRET = "secretKey"; //设置一个密钥
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");

        String url="http://localhost:8090/executeCode";
        //使用JSON来发送请求
        String json = JSONUtil.toJsonStr(executeCodeRequest);//把对象转换成JSON字符串
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"execute RemoteCodeSnadbox error,massage="+responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class); //把JSON转换成字符串
    }
}
